package com.zyasdk.util.root;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;

public class RootUtil {
	
	
	public static int isDeviceRooted() {
		if (checkRootMethod1()) {
			return 1;
		}
		if (checkRootMethod2()) {
			return 1;
		}
		if (checkRootMethod3()) {
			return 1;
		}
		return 0;
	}

	private static boolean checkRootMethod1() {
		String buildTags = android.os.Build.TAGS;

		if (buildTags != null && buildTags.contains("test-keys")) {
			return true;
		}
		return false;
	}

	private static boolean checkRootMethod2() {
		try {
			File file = new File("/system/app/Superuser.apk");
			if (file.exists()) {
				return true;
			}
		} catch (Exception e) {
		}

		return false;
	}

	private static boolean checkRootMethod3() {
		if (executeCommand(SHELL_CMD.check_su_binary) != null) {
			return true;
		} else {
			return false;
		}
	}

	private static ArrayList<String> executeCommand(SHELL_CMD shellCmd) {
		String line = null;
		ArrayList<String> fullResponse = new ArrayList<String>();
		Process localProcess = null;
		try {
			localProcess = Runtime.getRuntime().exec(shellCmd.command);
		} catch (Exception e) {
			return null;
		}
		// BufferedWriter out = new BufferedWriter(new
		// OutputStreamWriter(localProcess.getOutputStream()));
		BufferedReader in = new BufferedReader(new InputStreamReader(
				localProcess.getInputStream()));

		try {
			while ((line = in.readLine()) != null) {
				fullResponse.add(line);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return fullResponse;
	}

	public static enum SHELL_CMD {
		check_su_binary(new String[] { "/system/xbin/which", "su" }), ;
		String[] command;

		SHELL_CMD(String[] command) {
			this.command = command;
		}
	}
	
	
	/** 判断手机是否root，不弹出root请求框<br/> */
	public static boolean isRoot() {
		String binPath = "/system/bin/su";
		String xBinPath = "/system/xbin/su";
		if (new File(binPath).exists() && isExecutable(binPath))
			return true;
		if (new File(xBinPath).exists() && isExecutable(xBinPath))
			return true;
		return false;
	}

	private static boolean isExecutable(String filePath) {
		Process p = null;
		try {
			p = Runtime.getRuntime().exec("ls -l " + filePath);
			// 获取返回内容
			BufferedReader in = new BufferedReader(new InputStreamReader(
					p.getInputStream()));
			String str = in.readLine();
			if (str != null && str.length() >= 4) {
				char flag = str.charAt(3);
				if (flag == 's' || flag == 'x')
					return true;
			}
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			if(p!=null){
				p.destroy();
			}
		}
		return false;
	}

}
